package org.example.rowing.controller.raceProcessController;

import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.util.StringConverter;
import lombok.extern.slf4j.Slf4j;
import org.example.rowing.controller.LaneExportController;
import org.example.rowing.controller.util.NavigationUtil;
import org.example.rowing.domain.RegistrationWithAthlete;
import org.example.rowing.domain.RoundScore;
import org.example.rowing.service.*;
import org.example.rowing.vo.RaceVO;
import org.example.rowing.vo.RegistrationVO;
import org.example.rowing.vo.RoundScoreVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@Slf4j
public class LongDistanceProcessController {


    @FXML
    public Button randomButton;
    @FXML
    public Button nextRoundButton;
    @FXML
    public TableColumn<RoundScoreVO, String> statusColumn;
    @FXML
    public TableColumn<RoundScoreVO, String> athleteColumn;
    @FXML
    public TableColumn<RoundScoreVO, String> registrationIdColumn;
    @FXML
    public TableColumn<RoundScoreVO, String> teamNameColumn;
    @FXML
    public TableColumn<RoundScoreVO, Double> timeColumn;
    @FXML
    public TableView<RoundScoreVO> resultsTable;
    @FXML
    public Label currentRoundLabel;
    @FXML
    private TextField minutesInput;
    @FXML
    private TextField secondsInput;
    @FXML
    private TextField hundredthsInput;
    @FXML
    private ComboBox<RoundScoreVO> laneComboBox;
    @FXML
    public ComboBox<String> statusComboBox;
    private ObservableList<RoundScoreVO> resultsList;

    private Long raceId;
    private RaceVO raceVO;

    @Autowired
    private RaceInfoService raceInfoService;
    @Autowired
    private RaceProcessCommonService raceProcessCommonService;
    @Autowired
    private ProcessLongDistanceRaceService processLongDistanceRaceService;

    // 定义比赛阶段顺序
    private static final List<String> ROUND_ORDER = Arrays.asList(
            "预赛",
            "比赛结果"
    );

    @FXML
    public void initialize(RaceVO raceVO) {
        // 设置时间列的格式化显示
        timeColumn.setCellFactory(column -> new TableCell<RoundScoreVO, Double>() {
            @Override
            protected void updateItem(Double time, boolean empty) {
                super.updateItem(time, empty);

                if (empty || time == null) {
                    setText(null);
                } else {
                    // 格式化为 x1:x2.x3 格式
                    int minutes = (int) (time / 60);
                    int seconds = (int) (time % 60);
                    int hundredths = (int) ((time * 100) % 100);
                    setText(String.format("%d:%02d.%02d", minutes, seconds, hundredths));
                }
            }
        });

        // 设置表格列
        statusColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getStatus()));
        athleteColumn.setCellValueFactory(cellData -> {
            // 为每个单元格单独处理：获取当前行的运动员列表
            List<RegistrationWithAthlete> athletes = cellData.getValue().getRegistrationVO().getAthletes();

            // 动态拼接当前行所有运动员姓名
            String joinedNames = athletes.stream()
                    .map(RegistrationWithAthlete::getAthleteName)
                    .collect(Collectors.joining("、"));

            return new SimpleStringProperty(joinedNames);
        });
        registrationIdColumn.setCellValueFactory(cellData -> new SimpleStringProperty(String.valueOf(cellData.getValue().getRegistrationVO().getRegistrationId())));
        teamNameColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getRegistrationVO().getTeam().getName()));
        timeColumn.setCellValueFactory(cellData -> new ReadOnlyObjectWrapper<>(cellData.getValue().getScore()));
        statusComboBox.getSelectionModel().select("NORMAL");

        this.raceId = raceVO.getId();
        this.raceVO = raceVO;
        List<RegistrationVO> registrationVOS = raceProcessCommonService.getRegistrationVOS(raceVO);
        log.info("raceId---------------------------: {}", raceId);

        // 初始化赛事列表（默认展示一些数据）
        RoundScoreVO condition = new RoundScoreVO();
        condition.setRaceId(raceId);
        condition.setRound("预赛");
        List<RoundScoreVO> roundScoreVOS = raceInfoService.showRoundScoreByCondition(condition);

        if (roundScoreVOS.isEmpty()) {
            for (RegistrationVO registrationVO : registrationVOS) {
                RoundScore roundScore = new RoundScore(raceId, "预赛", null, null, null, registrationVO.getRegistrationId(), "NORMAL");
                raceInfoService.saveRoundScore(roundScore);
            }
            roundScoreVOS = raceInfoService.showRoundScoreByCondition(condition);
        }

        log.info("size {}", roundScoreVOS.size());
        resultsList = FXCollections.observableArrayList(roundScoreVOS);
        resultsTable.setItems(resultsList);

        // 初始化下拉框
        updateLaneComboBox();

        // 监听表格数据变化，自动更新下拉框
        resultsList.addListener((ListChangeListener<RoundScoreVO>) c -> {
            updateLaneComboBox();
        });
    }

    public void handleGenerateNextRound(ActionEvent event) {
        List<RoundScoreVO> curRounds = new ArrayList<>(resultsTable.getItems());
        boolean isDataValid = !curRounds.isEmpty() && curRounds.stream().allMatch(vo -> vo.getScore() != null);
        String currentRound = currentRoundLabel.getText();

        if (!isDataValid) {
            showErrorDialog("当前比赛未结束，无法晋级下一轮。请输入当前比赛的所有成绩！");
            return;
        }

        if (currentRound.equals("预赛")) {
            List<RoundScoreVO> rank = processLongDistanceRaceService.getRank(curRounds, raceVO);
            log.info("排名：{}", rank);
            updateRoundDisplay("比赛结果");
        } else {
            showErrorDialog("未知比赛阶段！");
        }

        log.info("晋级信息已更新");
    }

    public void handleTimeCommitClick(ActionEvent event) {
        RoundScoreVO selectedVO = laneComboBox.getSelectionModel().getSelectedItem();

        // 校验输入
        if (selectedVO == null) {
            showErrorDialog("请选择参赛队伍！");
            return;
        }

        String status = statusComboBox.getValue();
        double totalSeconds;

        if (!status.equals("NORMAL")) {
            totalSeconds = Double.MAX_VALUE;
            selectedVO.setStatus(status);
        } else {
            // 获取三个时间字段的值
            String minutesText = minutesInput.getText();
            String secondsText = secondsInput.getText();
            String hundredthsText = hundredthsInput.getText();

            if (minutesText == null || secondsText == null || hundredthsText == null ||
                    minutesText.isEmpty() || secondsText.isEmpty() || hundredthsText.isEmpty()) {
                showErrorDialog("请完整输入比赛用时！");
                return;
            }

            try {
                int minutes = Integer.parseInt(minutesText);
                int seconds = Integer.parseInt(secondsText);
                int hundredths = Integer.parseInt(hundredthsText);

                // 验证时间范围
                if (minutes < 0 || seconds < 0 || seconds > 59 || hundredths < 0 || hundredths > 99) {
                    showErrorDialog("时间输入无效！分钟≥0，秒(0-59)，百分秒(0-99)");
                    return;
                }

                // 计算总秒数
                totalSeconds = minutes * 60.0 + seconds + hundredths / 100.0;

                selectedVO.setStatus(status);
            } catch (NumberFormatException e) {
                showErrorDialog("时间必须为整数！");
                return;
            }
        }

        // 直接更新选中项的成绩
        selectedVO.setScore(totalSeconds);

        // 保存到数据库
        RoundScore roundScore = new RoundScore(
                selectedVO.getRaceId(),
                selectedVO.getRound(),
                null,
                selectedVO.getLane(),
                selectedVO.getScore(),
                selectedVO.getRegistrationVO().getRegistrationId(),
                selectedVO.getStatus()
        );
        raceInfoService.saveRoundScore(roundScore);

        // 清空输入
        minutesInput.clear();
        secondsInput.clear();
        hundredthsInput.clear();
        statusComboBox.getSelectionModel().select("NORMAL");
        laneComboBox.getSelectionModel().clearSelection();

        // 刷新表格（直接操作数据源，无需重新加载）
        resultsTable.refresh();
    }

    public void handlePrevRoundClick(ActionEvent event) {
        // 获取当前阶段索引
        int currentIndex = ROUND_ORDER.indexOf(currentRoundLabel.getText());

        // 如果当前是第一个阶段，无法回退
        if (currentIndex <= 0) {
            showErrorDialog("已经是第一个阶段！");
            return;
        }

        // 更新到上一阶段
        String prevRound = ROUND_ORDER.get(currentIndex - 1);
        updateRoundDisplay(prevRound);
    }

    public void handleNextRoundClick(ActionEvent event) {
        // 获取当前阶段索引
        int currentIndex = ROUND_ORDER.indexOf(currentRoundLabel.getText());

        // 如果当前是最后一个阶段，无法前进
        if (currentIndex >= ROUND_ORDER.size() - 1) {
            showErrorDialog("已经是最后一个阶段！");
            return;
        }

        // 更新到下一阶段
        String nextRound = ROUND_ORDER.get(currentIndex + 1);
        updateRoundDisplay(nextRound);
    }

    // 更新阶段显示和表格数据
    private void updateRoundDisplay(String round) {
        // 1. 更新阶段标签
        currentRoundLabel.setText(round);

        // 2. 加载对应阶段的数据
        RoundScoreVO condition = new RoundScoreVO();
        condition.setRaceId(raceId);
        condition.setRound(round);

        List<RoundScoreVO> roundData = raceInfoService.showRoundScoreByCondition(condition);

        // 3. 刷新表格
        resultsList.setAll(roundData);
        resultsTable.refresh();
    }

    private void updateLaneComboBox() {
        if (currentRoundLabel.getText().equals("比赛结果")) {
            laneComboBox.setItems(null);
        } else {
            // 直接绑定表格数据（假设 resultsList 是 ObservableList<RoundScoreVO>）
            laneComboBox.setItems(resultsList);
        }

        // 自定义下拉框显示内容
        laneComboBox.setCellFactory(param -> new ListCell<RoundScoreVO>() {
            @Override
            protected void updateItem(RoundScoreVO vo, boolean empty) {
                super.updateItem(vo, empty);
                setText(empty || vo == null ? "" : vo.getRegistrationVO().getRegistrationId() + "-" + vo.getRegistrationVO().getTeam().getName());
            }
        });

        // 自定义选中项显示内容（避免选中时显示对象地址）
        laneComboBox.setConverter(new StringConverter<RoundScoreVO>() {
            @Override
            public String toString(RoundScoreVO vo) {
                return vo == null ? "" : vo.getRegistrationVO().getRegistrationId() + "-" + vo.getRegistrationVO().getTeam().getName();
            }

            @Override
            public RoundScoreVO fromString(String lane) {
                // 若需支持手动输入，需实现反向解析（此处通常不需要）
                return null;
            }
        });
    }

    private void showErrorDialog(String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("输入错误");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
}
